#include "edepartmentchangeview.h"
#include "sqloperator.h"
#include <QDebug>
#include <QHeaderView>
#include <QColor>
#include <QPushButton>
#include <qcoreapplication.h>

EDepartmentChangeView::EDepartmentChangeView(EmployeeManager *employeeManager, const QString &empId, QWidget *parent) : 
    QWidget(parent),
    m_employeeManager(employeeManager),
    m_empId(empId),
    m_selectedRequestId(-1)
{
    initUI();
    loadDepartments();
    loadRequestHistory();
}

void EDepartmentChangeView::initUI()
{
    // 设置窗口标题
    setWindowTitle("部门调换申请");
    setMinimumSize(600, 500);

    // 创建主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);

    // 创建申请表单区域
    QWidget *formWidget = new QWidget;
    QVBoxLayout *formLayout = new QVBoxLayout(formWidget);

    // 部门选择
    QHBoxLayout *deptLayout = new QHBoxLayout;
    QLabel *deptLabel = new QLabel("目标部门:");
    m_deptComboBox = new QComboBox;
    deptLayout->addWidget(deptLabel);
    deptLayout->addWidget(m_deptComboBox);
    formLayout->addLayout(deptLayout);

    // 申请原因
    QHBoxLayout *reasonLayout = new QHBoxLayout;
    QLabel *reasonLabel = new QLabel("申请原因:");
    m_reasonTextEdit = new QTextEdit;
    m_reasonTextEdit->setMinimumHeight(100);
    reasonLayout->addWidget(reasonLabel);
    reasonLayout->addWidget(m_reasonTextEdit);
    formLayout->addLayout(reasonLayout);

    // 按钮布局
    QHBoxLayout *buttonLayout = new QHBoxLayout;
    m_submitButton = new QPushButton("提交申请");
    QPushButton *cancelButton = new QPushButton("撤销申请");
    buttonLayout->addWidget(m_submitButton);
    buttonLayout->addWidget(cancelButton);
    formLayout->addLayout(buttonLayout);

    // 连接撤销按钮信号槽
    connect(cancelButton, &QPushButton::clicked, this, &EDepartmentChangeView::onCancelRequest);

    // 状态标签
    m_statusLabel = new QLabel;
    m_statusLabel->setStyleSheet("color: blue;");
    formLayout->addWidget(m_statusLabel);

    mainLayout->addWidget(formWidget);

    // 创建申请历史表格
    m_requestTableWidget = new QTableWidget;
    m_requestTableWidget->setColumnCount(7);
    QStringList headers;
    headers << "申请ID" << "原部门" << "目标部门" << "申请原因" << "申请时间" << "状态";
    m_requestTableWidget->setHorizontalHeaderLabels(headers);
    m_requestTableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    mainLayout->addWidget(m_requestTableWidget);

    // 连接信号槽
    connect(m_submitButton, &QPushButton::clicked, this, &EDepartmentChangeView::onSubmitRequest);
    connect(m_requestTableWidget, &QTableWidget::cellClicked, this, &EDepartmentChangeView::onRequestTableItemClicked);
}

void EDepartmentChangeView::loadDepartments()
{
    SqlOperator sqlOperator;
    // 获取应用程序目录并构建数据库路径
    QString appDir = QCoreApplication::applicationDirPath();
    QString dbPath = appDir + "/../../sql/company.db";

    // 打开数据库连接
    if (!sqlOperator.open(dbPath, "departmentChangeConnection")) {
        m_statusLabel->setText("数据库连接失败: " + sqlOperator.lastError());
        m_statusLabel->setStyleSheet("color: red;");
        qDebug() << "数据库连接失败: " + sqlOperator.lastError();
        return;
    }

    // 查询所有部门
    QList<QString> fields = {"dept_id", "dept_name"};
    QList<QVariantList> data;

    if (sqlOperator.selectData("department", fields, QHash<QString, QVariant>(), data)) {
        foreach (const QVariantList &row, data) {
            int deptId = row[0].toInt();
            QString deptName = row[1].toString();
            m_deptComboBox->addItem(deptName, deptId);
        }
        m_statusLabel->setText("部门加载成功");
        m_statusLabel->setStyleSheet("color: green;");
    } else {
        m_statusLabel->setText("查询部门失败: " + sqlOperator.lastError());
        m_statusLabel->setStyleSheet("color: red;");
        qDebug() << "查询部门失败: " + sqlOperator.lastError();
    }

    sqlOperator.close();
}

void EDepartmentChangeView::loadRequestHistory()
{
    if (!m_employeeManager) {
        qDebug() << "EmployeeManager is null";
        return;
    }

    QVariantList requests = m_employeeManager->getDepartmentChangeRequests(m_empId);

    // 清空表格
    m_requestTableWidget->setRowCount(0);

    // 填充表格
    foreach (const QVariant &requestVar, requests) {
        QVariantHash request = requestVar.toHash();
        int row = m_requestTableWidget->rowCount();
        m_requestTableWidget->insertRow(row);

        m_requestTableWidget->setItem(row, 0, new QTableWidgetItem(request.value("request_id").toString()));
        m_requestTableWidget->setItem(row, 1, new QTableWidgetItem(request.value("old_dept_name").toString()));
        m_requestTableWidget->setItem(row, 2, new QTableWidgetItem(request.value("new_dept_name").toString()));
        m_requestTableWidget->setItem(row, 3, new QTableWidgetItem(request.value("reason").toString()));
        m_requestTableWidget->setItem(row, 4, new QTableWidgetItem(request.value("request_time").toString()));
        m_requestTableWidget->setItem(row, 5, new QTableWidgetItem(request.value("status").toString()));
    }
}

void EDepartmentChangeView::onRequestTableItemClicked(int row, int column)
{
    Q_UNUSED(column);
    // 获取选中行的申请ID
    QTableWidgetItem *item = m_requestTableWidget->item(row, 0);
    if (item) {
        m_selectedRequestId = item->text().toInt();
        // 高亮选中行
        for (int i = 0; i < m_requestTableWidget->rowCount(); ++i) {
            for (int j = 0; j < m_requestTableWidget->columnCount(); ++j) {
                QTableWidgetItem *tableItem = m_requestTableWidget->item(i, j);
                if (tableItem) {
                    if (i == row) {
                        tableItem->setBackground(QColor(173, 216, 230)); // 浅蓝色背景
                    } else {
                        tableItem->setBackground(QColor(255, 255, 255)); // 白色背景
                    }
                }
            }
        }
    }
}

void EDepartmentChangeView::onCancelRequest()
{
    if (m_selectedRequestId == -1) {
        m_statusLabel->setText("请先选择要撤销的申请");
        m_statusLabel->setStyleSheet("color: red;");
        return;
    }

    if (!m_employeeManager) {
        m_statusLabel->setText("撤销失败: 员工管理器为空");
        m_statusLabel->setStyleSheet("color: red;");
        return;
    }

    // 调用撤销申请方法
    bool success = m_employeeManager->cancelDepartmentChangeRequest(m_selectedRequestId);

    if (success) {
        m_statusLabel->setText("申请撤销成功");
        m_statusLabel->setStyleSheet("color: green;");
        m_selectedRequestId = -1; // 重置选中的申请ID
        loadRequestHistory(); // 刷新申请历史
    } else {
        m_statusLabel->setText("申请撤销失败，请重试");
        m_statusLabel->setStyleSheet("color: red;");
    }
}

void EDepartmentChangeView::onSubmitRequest()
{
    if (!m_employeeManager) {
        m_statusLabel->setText("提交失败: 员工管理器为空");
        m_statusLabel->setStyleSheet("color: red;");
        emit requestSubmitted(false);
        return;
    }

    // 获取选中的部门ID
    int newDeptId = m_deptComboBox->currentData().toInt();
    QString reason = m_reasonTextEdit->toPlainText();

    // 验证输入
    if (reason.isEmpty()) {
        m_statusLabel->setText("请输入申请原因");
        m_statusLabel->setStyleSheet("color: red;");
        return;
    }

    // 提交申请
    bool success = m_employeeManager->submitDepartmentChangeRequest(m_empId, newDeptId, reason);

    if (success) {
        m_statusLabel->setText("申请提交成功，请等待审核");
        m_statusLabel->setStyleSheet("color: green;");
        m_reasonTextEdit->clear();
        loadRequestHistory(); // 刷新申请历史
    } else {
        m_statusLabel->setText("申请提交失败，请重试");
        m_statusLabel->setStyleSheet("color: red;");
    }

    emit requestSubmitted(success);
}
